import Vue from 'vue';
import {
	baseUrl
} from './config.js'
import {
	mapState,
	mapMutations
} from 'vuex';
export default {
	install(Vue, opts) {
		Vue.prototype.$ajax = function ajax(url, data = {}, method = 'GET', showLoading = false, showMessage =
			true, header = {
				'content-type': 'application/x-www-form-urlencoded'
			}) {
			return new Promise((resolve, reject) => {
				if (showLoading) {
					uni.showLoading({
						mask: true
					})
				}
				if (uni.getStorageSync('userinfo') != '') {
					data.access_token = uni.getStorageSync('userinfo').access_token;
				}
				uni.request({
					url: baseUrl + url,
					data: data,
					method: method,
					header: header,
					success(res) {
						uni.hideLoading()
						uni.stopPullDownRefresh()
						if (res.data.resultCode == 1) {
							resolve(res.data);
						} else {
							// token过期
							if (res.data.resultMsg == '访问令牌过期或无效' || res.data.resultMsg ==
								'缺少访问令牌') {
								uni.showToast({
									title: '请先登录',
									icon: 'none',
									duration: 3000
								})
								uni.clearStorageSync()
								setTimeout(function() {
									uni.reLaunch({
										url: '/pages/login/login'
									})
								}, 1500)
								return
							}
							if (showMessage) {
								uni.showToast({
									title: res.data.resultMsg || '连接服务器失败,请稍后重试!',
									icon: 'none',
									duration: 3000
								})
							}


							reject(res.data)
						}
					},
					fail(e) {
						if (showMessage) {
							uni.showToast({
								title: res.data.resultMsg || '连接服务器失败,请稍后重试!',
								icon: 'none',
								duration: 3000
							})
						}
						uni.hideLoading()
					}
				})
			})
		}
	}
}
